<template>
  <div>
    <upload-excel-component
      :on-success="handleSuccess"
      :before-upload="beforeUpload"
    />
  </div>
</template>
<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { formatExcelDate } from '@/utils/index'
import { importEmployee } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    // 成功读出excel文件的内容
    async handleSuccess({ results, header }) {
      try {
        console.log('读出来的excel的内容是', results, header)
        this.tableData = results
        this.tableHeader = header
        const newData = this.transExcel(results, header)
        const res = await importEmployee(newData)
        this.$message.success(res.message)
        this.$router.push('/employees')
        console.log('转换之后的数据', newData)
      } catch (err) {
        this.$message.error(err)
      }
    },
    transExcel(results, header) {
      console.log('转换之前的数据', results, header)
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName',
        '聘用形式': 'formOfEmployment'
      }
      return results.map(item => {
        const obj = {}
        header.forEach(key => {
          if (mapInfo[key] === 'timeOfEntry' || mapInfo[key] === 'correctionTime') {
            obj[mapInfo[key]] = new Date(formatExcelDate(item[key]))
          } else {
            obj[mapInfo[key]] = item[key]
          }
        })
        return obj
      })
    }
  }
}
</script>
